from config import db
from sqlalchemy.sql import func
import enum
from utils import to_json

class TimestampMixin(object):
    created_at = db.Column(db.TIMESTAMP(timezone=True), server_default = func.now())
    updated_at =  db.Column(db.TIMESTAMP(timezone=True), server_default = func.now())

class Role(enum.Enum):
    admin=1
    user =2

class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.Text, unique=True, index=True)
    username = db.Column(db.Text)
    password_hash = db.Column(db.Text)
    role = db.Column(db.Enum(Role), default="user")
    docs = db.relationship('Doc', backref='user',  lazy='dynamic')
    created_at = db.Column(db.TIMESTAMP(timezone=True), server_default = func.now())
    updated_at =  db.Column(db.TIMESTAMP(timezone=True), server_default = func.now())

    def __repr__(self):
        return '<User %r>' % self.username


class Doc(TimestampMixin, db.Model):
    __tablename__ = 'docs'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Text, nullable=False)
    content = db.Column(db.Text, default="")
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    def __repr__(self):
        return '<Doc %r>' % self.title

class Banner(db.Model):
    __tablename__ = 'banners'

    id = db.Column(db.Integer, primary_key=True)
    path = db.Column(db.Text, default="")
    filename = db.Column(db.Text, default="")
    def __repr__(self):
        return '<Doc %r>' % self.title

class Spider(TimestampMixin, db.Model):
    __tablename__ = 'spiders'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.Text, default="")
    url = db.Column(db.Text, nullable=False)
    price = db.Column(db.Numeric, default=0)
    target_price = db.Column(db.Numeric, default=0)
    sku = db.Column(db.Text, default="")
    status = db.Column(db.Boolean, default=True, server_default='t')

    def __repr__(self):
        return '<Spider %r>' % self.title

    @property
    def json(self):
        return to_json(self, self.__class__)

    def as_dict(self):
       return {c.name: getattr(self, c.name) for c in self.__table__.columns}